package com.example.campuslink.commen.db.userNumber

import android.annotation.SuppressLint
import android.content.Context
import androidx.room.AutoMigration
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.campuslink.commen.db.InvitationTableConverter
import com.example.campuslink.commen.db.MessageBeanConverter
import com.example.campuslink.commen.db.UserInfoDataConverter
import db.ListStringConverter

@Database(entities = [UserNumberTable::class], version = 3, exportSchema = true)
@TypeConverters(
    ListStringConverter::class,
    InvitationTableConverter::class,
    MessageBeanConverter::class,
    UserInfoDataConverter::class
)
abstract class UserNumberData : RoomDatabase() {
    abstract fun userNumberDao(): UserNumberDao
    // 安全迁移：检查列是否存在
    private val MIGRATION_1_2 = object : Migration(1, 2) {
        @SuppressLint("Range")
        override fun migrate(database: SupportSQLiteDatabase) {
            if (!columnExists(database, "user_number_table", "username")) {
                database.execSQL(
                    "ALTER TABLE user_number_table ADD COLUMN username TEXT NOT NULL DEFAULT ''"
                )
            }
            // 添加其他必要变更
            // if (!columnExists(database, "user_number_table", "new_column")) { ... }
        }

        @SuppressLint("Range")
        private fun columnExists(db: SupportSQLiteDatabase, table: String, column: String): Boolean {
            db.query("PRAGMA table_info($table)").use { cursor ->
                while (cursor.moveToNext()) {
                    if (cursor.getString(cursor.getColumnIndex("name")) == column) {
                        return true
                    }
                }
            }
            return false
        }
    }

    val MIGRATION_2_3 = object : Migration(2, 3) {
        override fun migrate(database: SupportSQLiteDatabase) {
            database.execSQL("ALTER TABLE user_number_table ADD COLUMN userInfoData TEXT DEFAULT NULL")
        }
    }


    companion object {
        @Volatile
        private var INSTANCE: UserNumberData? = null

        fun getDatabase(context: Context): UserNumberData {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    UserNumberData::class.java,
                    "user_number_dataBase"
                )
                    .fallbackToDestructiveMigration()  // 开发环境安全网
                    .build()
                INSTANCE = instance
                instance
            }
        }
    }

}